package com.ruicar.afs.cloud.seats.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.bizcommon.rules.entity.AfsRuleInfo;
import com.ruicar.afs.cloud.bizcommon.rules.service.impl.AfsRuleInfoServiceImpl;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.seats.condition.RegularValueCondition;
import com.ruicar.afs.cloud.seats.entity.RegularValue;
import com.ruicar.afs.cloud.seats.mapper.RegularValueMapper;
import com.ruicar.afs.cloud.seats.service.RegularValueService;
import com.ruicar.afs.cloud.seats.util.RuleState;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author tiankai
 * @Describe 规则数值
 * Created on 2020-06-08
 */
@Slf4j
@RestController
@RequestMapping("/group")
@AllArgsConstructor
@Api(description = "优先级,分单时间规则接口")
public class RegularValueController {

    @Autowired
    private RegularValueService service;
    private RegularValueMapper mapper;
    private AfsRuleInfoServiceImpl afsRuleInfoService;

    @RequestMapping(value = "/addRegularValue", method = RequestMethod.POST)
    @ApiOperation(value = "保存参数值")
    public IResponse<Boolean> addRegularValue(@RequestBody RegularValue regularValue) {
        RegularValue value = service.getById(regularValue.getId());
        if (ObjectUtil.isNull(value)) {
            value = new RegularValue();
            if(ObjectUtil.isNotNull(checkRuleName(regularValue.getRuleType(),regularValue.getRegulationName()))){
                return new IResponse<Boolean>().setCode(CommonConstants.FAIL).setData(false).setMsg("此规则名称已存在,请重新填写");
            }
            value.setValue(regularValue.getValue());
            value.setRuleType(regularValue.getRuleType());
            value.setRuleState(RuleState.EFFECTIVE.getCode());
            value.setRegulationName(regularValue.getRegulationName());
        }else{
            if(!regularValue.getRegulationName().equals(value.getRegulationName())){
                if(ObjectUtil.isNotNull(checkRuleName(regularValue.getRuleType(),regularValue.getRegulationName()))){
                    return new IResponse<Boolean>().setCode(CommonConstants.FAIL).setData(false).setMsg("此规则名称已存在,请重新填写");
                }
            }
            value.setValue(regularValue.getValue());
            value.setRuleType(regularValue.getRuleType());
            value.setRegulationName(regularValue.getRegulationName());
        }
        service.saveOrUpdate(value);
        return new IResponse().setData(true);
    }

    @RequestMapping(value = "/addSplittingTime", method = RequestMethod.POST)
    @ApiOperation(value = "保存分单时间")
    public IResponse<Boolean> addSplittingTime(@RequestBody RegularValueCondition condition) {
        String time = "";
        List list = condition.getTime();
        for (int i = 0; i < list.size(); i++) {
            time = time + "-" + list.get(i);
        }
        RegularValue value = service.getById(condition.getId());
        if (ObjectUtil.isNull(value)) {
            if(ObjectUtil.isNotNull(checkRuleName(condition.getRuleType(),condition.getRegulationName()))){
                return new IResponse<Boolean>().setCode(CommonConstants.FAIL).setData(false).setMsg("此规则名称已存在,请重新填写");
            }
            value = new RegularValue();
            value.setValue(time.substring(1));
            value.setRuleType(condition.getRuleType());
            value.setRuleState(RuleState.EFFECTIVE.getCode());
            value.setRegulationName(condition.getRegulationName());
        }else{
            if(!condition.getRegulationName().equals(value.getRegulationName())){
                if(ObjectUtil.isNotNull(checkRuleName(condition.getRuleType(),condition.getRegulationName()))){
                    return new IResponse<Boolean>().setCode(CommonConstants.FAIL).setData(false).setMsg("此规则名称已存在,请重新填写");
                }
            }
            value.setValue(time.substring(1));
            value.setRuleType(condition.getRuleType());
            value.setRegulationName(condition.getRegulationName());
        }
        service.saveOrUpdate(value);
        return new IResponse().setData(true);
    }

    @RequestMapping(value = "/addProcedure", method = RequestMethod.POST)
    @ApiOperation(value = "保存流程匹配规则参数")
    public IResponse<Boolean> addProcedure(@RequestBody RegularValueCondition condition) {
        RegularValue value = service.getById(condition.getId());
        if (ObjectUtil.isNull(value)) {
            if(ObjectUtil.isNotNull(checkRuleName(condition.getRuleType(),condition.getRegulationName()))){
                return new IResponse<Boolean>().setCode(CommonConstants.FAIL).setData(false).setMsg("此规则名称已存在,请重新填写");
            }
            value = new RegularValue();
            value.setValue(condition.getProcessNo() + "#" + condition.getValue());
            value.setRuleType(condition.getRuleType());
            value.setRuleState(RuleState.EFFECTIVE.getCode());
            value.setRegulationName(condition.getRegulationName());
        }else{
            if(!condition.getRegulationName().equals(value.getRegulationName())){
                if(ObjectUtil.isNotNull(checkRuleName(condition.getRuleType(),condition.getRegulationName()))){
                    return new IResponse<Boolean>().setCode(CommonConstants.FAIL).setData(false).setMsg("此规则名称已存在,请重新填写");
                }
            }
            value.setValue(condition.getProcessNo() + "#" + condition.getValue());
            value.setRuleType(condition.getRuleType());
            value.setRegulationName(condition.getRegulationName());
        }
        service.saveOrUpdate(value);
        return new IResponse().setData(true);
    }

    @RequestMapping(value = "/addTop", method = RequestMethod.POST)
    @ApiOperation(value = "保存置顶规则信息")
    public IResponse<Boolean> addTop(@RequestBody RegularValueCondition condition) {
        List<RegularValue> list = service.list((Wrappers.<RegularValue>query().lambda().eq(RegularValue::getRuleType, condition.getRuleType())).eq(RegularValue::getRegulationName, condition.getRegulationName()));
        if(list!=null&&!list.isEmpty()){
            return new IResponse<Boolean>().setCode(CommonConstants.FAIL).setData(false).setMsg("此规则名称已存在,请重新填写");
        }
        RegularValue value = service.getById(condition.getId());
        if (ObjectUtil.isNull(value)) {
            value = new RegularValue();
            value.setRuleType(condition.getRuleType());
            value.setRuleState(RuleState.EFFECTIVE.getCode());
            value.setRegulationName(condition.getRegulationName());
        }
        value.setRuleType(condition.getRuleType());
        value.setRegulationName(condition.getRegulationName());
        service.saveOrUpdate(value);
        return new IResponse().setData(true);
    }

    @RequestMapping(value = "/updateRuleState", method = RequestMethod.POST)
    @ApiOperation(value = "修改规则状态")
    public IResponse<RegularValue> updateRuleState(@RequestBody RegularValueCondition condition) {
        RegularValue regularValue = service.getById(condition.getId());
        if (RuleState.EFFECTIVE.getCode().equals(condition.getRuleState())) {
            afsRuleInfoService.activeRule(condition.getRuleId());
            regularValue.setRuleState(RuleState.INVALID.getCode());
        } else if (RuleState.INVALID.getCode().equals(condition.getRuleState())) {
            afsRuleInfoService.deActiveRule(condition.getRuleId());
            afsRuleInfoService.expiredRule(condition.getRuleId());
            regularValue.setRuleState(RuleState.EFFECTIVE.getCode());
        } else {
            regularValue.setRuleState(RuleState.EFFECTIVE.getCode());
        }
        service.saveOrUpdate(regularValue);
        return new IResponse().setData(true);
    }

    @RequestMapping(value = "/updateTopPriorityRule", method = RequestMethod.POST)
    @ApiOperation(value = "修改置顶，优先级规则状态")
    public IResponse<RegularValue> updateTopPriorityRule(@RequestBody AfsRuleInfo ruleInfo) {
        if (RuleState.ACTIVE.getCode().equalsIgnoreCase(ruleInfo.getStatus().toString())
                || RuleState.NEW.getCode().equalsIgnoreCase(ruleInfo.getStatus().toString())) {
            afsRuleInfoService.deActiveRule(ruleInfo.getId());
            afsRuleInfoService.expiredRule(ruleInfo.getId());
        } else {
            afsRuleInfoService.activeRule(ruleInfo.getId());
        }
        return new IResponse().setData(true);
    }

    @GetMapping(value = {"/queryRegularValue"})
    @ApiOperation(value = "获取优先级（分页）")
    public IResponse<IPage<RegularValueCondition>> queryRegularValue(@ModelAttribute RegularValueCondition condition) {
        IPage<List<RegularValueCondition>> list = mapper.getValueInfo(new Page(condition.getPageNumber(), condition.getPageSize()), condition);
        return IResponse.success(list);
    }

    @GetMapping(value = {"/getAfsRuleInfo"})
    @ApiOperation(value = "获取置顶规则（分页）")
    public IResponse<IPage<RegularValueCondition>> getAfsRuleInfo(@ModelAttribute RegularValueCondition condition) {
        IPage<List<RegularValueCondition>> list = mapper.getAfsRuleInfo(new Page(condition.getPageNumber(), condition.getPageSize()), condition);
        return IResponse.success(list);
    }

    public RegularValue checkRuleName(String ruleType,String ruleName){
        RegularValue regularValue = service.getOne((Wrappers.<RegularValue>query().lambda().eq(RegularValue::getRuleType, ruleType)).eq(RegularValue::getRegulationName, ruleName));
        return regularValue;
    }
}
